package top.shiyiri.map;

import org.junit.Test;

import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * @author Aunean
 * @date 2022/1/6
 */
/*
向TreeMap中添加key-value，要求key必须是有同一个类创建的对象
因为要按照key进行排序：自然排序、定制排序
 */
public class TreeMapTest {

    @Test
    public void test1() {
        TreeMap<User, Object> treeMap = new TreeMap<>();

        User u1 = new User("Tom", 23);
        User u2 = new User("Jerry", 13);
        User u3 = new User("Jack", 26);
        User u4 = new User("Rose", 15);

        treeMap.put(u1, 90);
        treeMap.put(u2, 70);
        treeMap.put(u3, 20);
        treeMap.put(u4, 40);

        Set<Map.Entry<User, Object>> entries = treeMap.entrySet();
        for (Map.Entry<User, Object> en: entries) {
            System.out.println(en);
        }
    }

    //定制排序
    @Test
    public void test2() {
        TreeMap<User, Integer> treeMap = new TreeMap<>(new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof User && o2 instanceof User) {
                    User u1 = (User) o1;
                    User u2 = (User) o2;
                    return Integer.compare(u1.getAge(), u2.getAge());
                }
                throw new RuntimeException("输入的类型不匹配");
            }
        });

        User u1 = new User("Tom", 23);
        User u2 = new User("Jerry", 13);
        User u3 = new User("Jack", 26);
        User u4 = new User("Rose", 15);

        treeMap.put(u1, 90);
        treeMap.put(u2, 70);
        treeMap.put(u3, 20);
        treeMap.put(u4, 40);

        Set<Map.Entry<User, Integer>> entries = treeMap.entrySet();
        for (Map.Entry<User, Integer> en: entries) {
            System.out.println(en);
        }
    }
}
